package com.example.tupiancs34;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ImagePagerAdapter extends RecyclerView.Adapter<ImagePagerAdapter.ImageViewHolder> {

    private Context context;
    private List<String> imagePaths;

    public ImagePagerAdapter(Context context) {
        this.context = context;
        this.imagePaths = generateImageList();
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image_simple, parent, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        try {
            // 从assets加载图片
            InputStream is = context.getAssets().open(imagePaths.get(position));
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            holder.imageView.setImageBitmap(bitmap);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return imagePaths.size();
    }

    /**
     * 获取指定位置的图片文件名（不包含路径）
     */
    public String getImageFileName(int position) {
        if (position >= 0 && position < imagePaths.size()) {
            String fullPath = imagePaths.get(position);
            return fullPath.substring(fullPath.lastIndexOf("/") + 1);
        }
        return null;
    }

    private List<String> generateImageList() {
        List<String> images = new ArrayList<>();
        // 生成70张webp图片的文件名
        for (int i = 1; i <= 70; i++) {
            images.add(String.format("images/image_%03d.webp", i));
        }
        return images;
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }
}